package org.ala.tiktools_clickhouse_generator.generator;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;

import org.ala.tiktools_clickhouse_generator.config.ConfigInfo;
import org.ala.tiktools_clickhouse_generator.conn.ConnectionHolder;
import org.ala.tiktools_clickhouse_generator.generator.dao.DaoCreator;
import org.ala.tiktools_clickhouse_generator.generator.dao.DaoInfo;
import org.ala.tiktools_clickhouse_generator.generator.entity.EntityCreator;
import org.ala.tiktools_clickhouse_generator.generator.entity.EntityInfo;
import org.ala.tiktools_clickhouse_generator.generator.fields.FieldsCreator;
import org.ala.tiktools_clickhouse_generator.generator.fields.FieldsInfo;
import org.ala.tiktools_clickhouse_generator.generator.mapper.MapperCreator;
import org.ala.tiktools_clickhouse_generator.generator.mapper.MapperInfo;
import org.ala.tiktools_clickhouse_generator.generator.query.QueryCreator;
import org.ala.tiktools_clickhouse_generator.generator.query.QueryInfo;
import org.ala.tiktools_clickhouse_generator.table.TableInfo;
import org.ala.tiktools_clickhouse_generator.table.TableInfoParser;

import freemarker.template.TemplateException;

/**
 *	生成器
 *
 *	@author ala
 *	@date 2025年6月9日
 */
public class Creator {

	
	protected ConnectionHolder ch;
	
	protected EntityCreator entityCreator = new EntityCreator();
	protected QueryCreator queryCreator = new QueryCreator();
	protected FieldsCreator fieldsCreator = new FieldsCreator();
	protected DaoCreator daoCreator = new DaoCreator();
	protected MapperCreator mapperCreator = new MapperCreator();
	
	/**
	 * 	生成
	 * @throws SQLException 
	 */
	public void create(ConfigInfo config) throws SQLException {
		//	那链接
		ch = new ConnectionHolder(config.getDbms().getUrl(), config.getDbms().getUsername(), config.getDbms().getPassword());
		
		//	表信息
		Arrays.stream(config.getPart().getTables()).forEach(table -> {
			try {
				createTable(config, table, ch.getConnection());
			} catch (SQLException | IOException | TemplateException e) {
				e.printStackTrace();
			}
		});
		
		//	生成Entity
		System.out.println("生成结束.");
	}
	
	
	/**
	 * 	生成表相关的代码
	 * 	@throws SQLException 
	 * @throws TemplateException 
	 * @throws IOException 
	 */
	public void createTable(ConfigInfo config, String table, Connection conn) throws SQLException, IOException, TemplateException {
		TableInfo ti = TableInfoParser.parseTableInfo(table, ch.getConnection());
		
		//	生成Entity
		EntityInfo ei = entityCreator.create(config, ti);
		//	生成Query
		QueryInfo qi = queryCreator.create(config, ti, ei);
		//	生成Fields
		FieldsInfo fi = fieldsCreator.create(config, ti, ei);
		
		//	生成Dao
		DaoInfo di = daoCreator.create(config, ti, ei, qi);
		
		//	生成Mapper
		MapperInfo mi = mapperCreator.create(config, ti, ei, di);
		
		System.out.println("生成table:" + table + " 结束.");
	}
	
}
